package com.rain.shoppingscienceproj.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import com.google.gson.Gson;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.module.JsonBean;
import com.rain.shoppingscienceproj.module.MyMap;
import com.rain.shoppingscienceproj.module.MycolorArea;
import com.rain.shoppingscienceproj.module.address.City;
import com.rain.shoppingscienceproj.module.address.County;
import com.rain.shoppingscienceproj.module.address.Province;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.ColorChangeHelp;
import com.rain.shoppingscienceproj.ui.utile.SvgUtil;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.ui.view.MyMapView;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.CustomTopBar;
import com.rain.shoppingscienceproj.utils.GetJsonDataUtil;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapActivity extends BaseActivity implements OptionPicker.OnOptionSelectListener {

    @BindView(R.id.map_view)
    MyMapView myMapView;
    private MyMap myMap;
    private HashMap<String, List<MycolorArea>> colorView_hashmap;
    private String provinceName = "", provinceId = "";
    private String provinceIds, cityId, countyId, nickName = "", phone = "", detailedAddress = "", address = "";
    private OptionPicker mPicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleRightText(this, "选择代理省份", "完成");
//        loadingDialog = new LoadingDialog(this, "正在加载...");
        userInfo = GlobalData.getUserInfo();
        //设置颜色渐变条
        setColorView();
        //初始化map
        initMap();
        //初始化map各省份颜色
        ColorChangeHelp.changeMapColors(myMap, ColorChangeHelp.nameStrings[0]);
        myMapView.chingeMapColors();
        initListener();
        addressShow();
    }

    private void addressShow() {
        mPicker = new OptionPicker.Builder(this, 3, this).create();
        final DefaultCenterDecoration decoration = new DefaultCenterDecoration(this);
        decoration.setLineColor(getResources().getColor(R.color.colorPrimary))
                .setLineWidth(1)
                .setMargin(Util.dip2px(this, 10), Util.dip2px(this, -3), Util.dip2px(this, 10),
                        Util.dip2px(this, -3));

        mPicker = new OptionPicker.Builder(this, 3, this).setInterceptor(new BasePicker.Interceptor() {
            @Override
            public void intercept(PickerView pickerView) {
                int level = (int) pickerView.getTag();
                pickerView.setVisibleItemCount(5);
                // setInterceptor 可以根据level区分设置pickerview属性
                pickerView.setCenterDecoration(decoration);
                pickerView.setColor(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.text_color));
                pickerView.setTextSize(15, 20);
            }
        }).create();
        int padding = Util.dip2px(this, 20);
        mPicker.setPadding(0, padding, 0, padding);
        Dialog dialog = mPicker.getPickerDialog();
        dialog.setCanceledOnTouchOutside(true);
        //dialog.getWindow().setGravity(Gravity.BOTTOM);

        // 自定义topbar
        CustomTopBar topBar = new CustomTopBar(mPicker.getRootLayout());
        topBar.getTitleView().setText("请选择城市");
        topBar.setDividerHeight(1).setDividerColor(Color.parseColor("#eeeeee"));
        mPicker.setTopBar(topBar);

        List<Province> data = createData();
        mPicker.setDataWithValues(data);
    }

    private List<Province> createData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        List<Province> list = new ArrayList<>();
        for (int i = 0; i < jsonBean.size(); i++) {
            Province province = new Province();
            province.name = jsonBean.get(i).getName();
            province.citys = new ArrayList<>();
            for (int j = 0; j < jsonBean.get(i).getCityList().size(); j++) {
                City city = new City();
                city.name = jsonBean.get(i).getCityList().get(j).getName();
                city.counties = new ArrayList<>();
                for (int k = 0; k < jsonBean.get(i).getCityList().get(j).getArea().size(); k++) {
                    County county = new County();
                    county.name = jsonBean.get(i).getCityList().get(j).getArea().get(k);
                    city.counties.add(county);
                }
                province.citys.add(city);
            }
            list.add(province);
        }
        return list;
    }

    private ArrayList<JsonBean> parseData(String result) {
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    @OnClick(R.id.rl_right)
    void sub() {
        mPicker.setSelectedWithValues(provinceId, cityId, countyId);
        mPicker.show();

        if ("".equals(provinceId)) {
            ToastUtils.showShortToast("请选择代理人省份");
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("text", provinceId);
        intent.putExtra("provinceName", provinceName);
        setResult(103, intent);
        finish();
    }

    private void initListener() {
        myMapView.setOnChoseProvince((provincename, id) -> {
            provinceName = provincename;
            provinceId = id;
        });
    }


    private void setColorView() {
        colorView_hashmap = new HashMap<>();
        for (int i = 0; i < ColorChangeHelp.nameStrings.length; i++) {
            String colors[] = ColorChangeHelp.colorStrings[i].split(",");
            String texts[] = ColorChangeHelp.textStrings[i].split(",");
            List<MycolorArea> list = new ArrayList<>();
            for (int j = 0; j < colors.length; j++) {
                MycolorArea c = new MycolorArea();
                c.setColor(Color.parseColor(colors[j]));
                c.setText(texts[j]);
                list.add(c);
            }
            colorView_hashmap.put(ColorChangeHelp.nameStrings[i], list);
        }
    }

    private void initMap() {
        //拿到SVG文件，解析成对象
        myMap = new SvgUtil(this).getProvinces();
        //设置缩放最大和最小倍数
        myMapView.setMaxScale(3);
        myMapView.setMinScale(1);
        //传数据
        myMapView.setMap(myMap);
    }

    @Override
    public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
        Province province = (Province) selectedOptions[0];
        City city = (City) selectedOptions[1];
        County county = (County) selectedOptions[2];
        provinceIds = province.name;
        cityId = city.name;
        countyId = county.name;
        address = province.name + "-" + city.name + "-" + county.name;
//        tv_area.setText(address);
    }
}
